package com.Luoyi.springframework.context.support;

import com.Luoyi.springframework.beans.BeansException;
import com.Luoyi.springframework.beans.factory.config.BeanPostProcessor;
import com.Luoyi.springframework.context.ApplicationContext;
import com.Luoyi.springframework.context.ApplicationContextAware;

public class ApplicationContextAwareProcessor implements BeanPostProcessor {
    private final ApplicationContext applicationContext;

    public ApplicationContextAwareProcessor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    //在Bean初始化前（BeforeInitialization阶段）进行回调处理
    //专用于向Bean注入ApplicationContext容器引用
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        /*检查当前Bean是否实现了ApplicationContextAware接口
      通过类型强制转换调用setApplicationContext()方法
      将成员变量applicationContext注入到目标Bean中*/
        if (bean instanceof ApplicationContextAware){
            ((ApplicationContextAware)bean).setApplicationContext(applicationContext);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
